package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.OrderItemAdapter;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.entity.OrderDetail;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "OrderDetailActivity";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    private ListView mListView;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private OrderItemAdapter mAdapter;
    private List<OrderDetail> productList = new ArrayList<>();
    TextView tv_salebillid;
    TextView tv_salebilldate;
    TextView tv_customer;
    TextView tv_selectck;
    TextView tv_shouhuoren;
    TextView tv_shouhuotel;
    TextView tv_shouhuodizhi;
    TextView tv_comment;
    TextView tv_num;
    String orderId;
    String storeHouseId;
    boolean isDMS =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        mContext = this;
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        initView();
        //initData();
    }

    private void initData() {
        try {
            String url = NetUtils.ORDER_DETAIL;
            String param = url + orderId + "&userId=" + SharedPreference.getPreferString("id");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(param, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else {
                            sendMessagea(UPLOAD_FAIL, "fail");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "fail");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    sendMessagea(UPLOAD_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    JSONObject jsonObejct = JSONObject.parseObject(msg.obj.toString());
                    if (jsonObejct.getJSONObject("data") != null) {
                        JSONObject data = jsonObejct.getJSONObject("data");
                        if (!StringUtil.isEmpty(data.getString("total"))) {
                            tv_num.setText(data.getString("total") + "件");
                        }
                        if (data.getJSONArray("rows") != null) {
                            productList = JSONArray.parseArray(data.getJSONArray("rows").toString(), OrderDetail.class);
                            if (productList.size() > 0) {
                                mAdapter = new OrderItemAdapter(mContext, productList, storeHouseId, isDMS);
                                mListView.setAdapter(mAdapter);
                                Utils.setListViewHeightBasedOnChildren(mListView);
                                Log.d(TAG, "result " + productList.size());
                            }
                        }
                    }
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    break;
                default:
                    break;
            }
        }
    };


    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    private void initView() {
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("订单详情");

        tv_salebillid = (TextView) findViewById(R.id.tv_salebillid);
        tv_salebilldate = (TextView) findViewById(R.id.tv_salebilldate);
        tv_customer = (TextView) findViewById(R.id.tv_customer);
        tv_selectck = (TextView) findViewById(R.id.tv_selectck);
        tv_shouhuoren = (TextView) findViewById(R.id.tv_shouhuoren);
        tv_shouhuotel = (TextView) findViewById(R.id.tv_shouhuotel);
        tv_shouhuodizhi = (TextView) findViewById(R.id.tv_shouhuodizhi);
        tv_comment = findViewById(R.id.tv_comment);
        tv_num = (TextView) findViewById(R.id.tv_num);
        mListView = (ListView) findViewById(R.id.orderDetailListView);

        FindOrderDetail findOrderDetail = (FindOrderDetail) getIntent().getExtras().get("order");
        //orderId = findOrderDetail.getOrderId();
        storeHouseId = findOrderDetail.getStoreHouseId();
        if(!StringUtil.isEmpty(findOrderDetail.getDmsOrderId())){
            isDMS = true;
            tv_salebillid.setText(findOrderDetail.getDmsOrderId());
        } else {
            isDMS = false;
            tv_salebillid.setText(findOrderDetail.getOrderId());
        }
        if (StringUtil.isEmpty(findOrderDetail.getHouseName())) {
            tv_salebilldate.setText(findOrderDetail.getCustmerName());
        } else {
            tv_salebilldate.setText(findOrderDetail.getHouseName());
        }
        tv_customer.setText(findOrderDetail.getOrderDate());
        tv_selectck.setText(App.df.format(Double.valueOf(findOrderDetail.getOrderTotalPrice())));
        if(StringUtil.isEmpty(findOrderDetail.getCommunicatePeople())){
            tv_shouhuoren.setText(tv_salebilldate.getText().toString());
        } else {
            tv_shouhuoren.setText(findOrderDetail.getCommunicatePeople() + "");
        }
        if(StringUtil.isEmpty(findOrderDetail.getTelephone())){
            tv_shouhuotel.setText("");
        } else {
            tv_shouhuotel.setText(findOrderDetail.getTelephone() + "");
        }

        tv_shouhuodizhi.setText(findOrderDetail.getDstAddr() + "");
        if(StringUtil.isEmpty(findOrderDetail.getComment())){
            tv_comment.setText("");
        } else {
            tv_comment.setText(findOrderDetail.getComment() + "");
        }

        String orderDetailList = findOrderDetail.getOrderDetailList();
        if (StringUtil.isEmpty(orderDetailList)) {
            tv_num.setText("0件");
        } else {
            productList = JSONArray.parseArray(orderDetailList, OrderDetail.class);
            tv_num.setText(productList.size() + "件");
            if (productList.size() > 0) {
                mAdapter = new OrderItemAdapter(mContext, productList,storeHouseId, isDMS);
                mListView.setAdapter(mAdapter);
                Utils.setListViewHeightBasedOnChildren(mListView);
                Log.d(TAG, "result " + productList.size());
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
            default:
                break;
        }
    }
}
